package top.rainf.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import top.rainf.constants.AttributeConstants;
import top.rainf.constants.UserConstants;
import top.rainf.service.IEmailService;
import top.rainf.support.Result;
import top.rainf.support.VerifyCodeGenerator;
import top.rainf.support.VerifyUtil;
import top.rainf.util.CookieSetter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 星环
 * @date 2023/5/6 19:52:47
 * @description
 */
@RestController
@Slf4j
@RequestMapping("/email")
public class PostEmailController {
    @Autowired
    IEmailService sendEmailService;
    @RequestMapping("/verify")
    public Result sendVerifyEmail(@RequestParam("to_email") String toEmail, HttpServletRequest request, HttpServletResponse response){
        //验证邮箱
        if(!VerifyUtil.isValidEmail(toEmail)){
            System.out.println("无效");
            return Result.fail("邮箱无效");
        }
        String code = VerifyCodeGenerator.generateVerifyCode(6);
        //将验证码加入session
        new CookieSetter(request,response).setSessionAttr(AttributeConstants.REAL_CODE,code);

        //把code发送给用户邮箱
        Thread thread = new Thread(()->{
            log.info("正在发送邮件。。。");
            long time = System.currentTimeMillis();
            sendEmailService.sendEmail(toEmail , "----语扉论坛验证码---","欢迎使用语扉论坛！这是您的验证码：\n" + code);
            log.info("发送邮件完毕,用时{}毫秒",System.currentTimeMillis() - time);
        });
        thread.start();
        //thread.
        return Result.success();
    }


}
